import Vue from 'vue';
import ModernModal from '@/components/Dialog';

// 创建构造器
const ModalConstructor = Vue.extend(ModernModal);

// 实例容器
const instances = [];
let seed = 1;

/**
 * 创建实例并显示弹窗
 * @param {Object} options - 弹窗配置选项
 * @returns {Object} 弹窗实例
 */
const showModal = (options = {}) => {
  // 生成唯一ID
  const id = `modal_${seed++}`;

  // 创建实例
  const instance = new ModalConstructor({
    propsData: {
      ...options
    }
  });

  // 设置ID
  instance.id = id;

  // 挂载到body
  instance.$mount();
  document.body.appendChild(instance.$el);

  // 设置主题
  if (options.theme) {
    instance.$el.setAttribute('data-theme', options.theme);
  }

  // 打开弹窗
  instance.open();

  // 添加到实例列表
  instances.push(instance);

  // 监听关闭事件，自动清理
  instance.$once('hook:beforeDestroy', () => {
    removeInstance(instance);
    if (instance.$el && instance.$el.parentNode) {
      instance.$el.parentNode.removeChild(instance.$el);
    }
  });

  return instance;
};

/**
 * 从实例列表中移除实例
 * @param {Object} instance - 要移除的实例
 */
const removeInstance = (instance) => {
  if (!instance) return;
  const index = instances.findIndex(inst => inst.id === instance.id);
  if (index !== -1) {
    instances.splice(index, 1);
  }
};

/**
 * 关闭指定实例
 * @param {Object} instance - 要关闭的实例
 */
const closeModal = (instance) => {
  if (!instance) return;
  instance.close();
  setTimeout(() => {
    if (instance.$el && instance.$el.parentNode) {
      instance.$el.parentNode.removeChild(instance.$el);
    }
    instance.$destroy();
  }, 300);
};

/**
 * 关闭所有弹窗
 */
const closeAllModals = () => {
  [...instances].forEach(instance => {
    closeModal(instance);
  });
};

// 弹窗服务
const Dialog = {
  /**
   * 显示自定义弹窗
   * @param {Object} options - 弹窗配置
   * @returns {Object} 弹窗实例
   */
  show(options = {}) {
    return showModal(options);
  },

  /**
   * 显示确认弹窗
   * @param {Object|String} options - 弹窗配置或内容字符串
   * @returns {Promise} 返回用户选择结果的Promise
   */
  confirm(options = {}) {
    if (typeof options === 'string') {
      options = {content: options};
    }

    return new Promise((resolve) => {
      const instance = showModal({
        title: options.title || '确认',
        content: options.content,
        showCancel: true,
        showConfirm: true,
        cancelText: options.cancelText || '取消',
        confirmText: options.confirmText || '确定',
        closeOnClickOverlay: options.closeOnClickOverlay ?? false,
        type: options.type || 'default',
        ...options
      });

      // 监听确认事件
      instance.$once('confirm', () => {
        resolve(true);
      });

      // 监听取消和关闭事件
      instance.$once('cancel', () => {
        resolve(false);
      });

      instance.$once('close', () => {
        if (!instance.confirmed && !instance.canceled) {
          resolve(false);
        }
      });
    });
  },

  /**
   * 显示提示弹窗
   * @param {Object|String} options - 弹窗配置或内容字符串
   * @returns {Promise} 返回Promise
   */
  alert(options = {}) {
    if (typeof options === 'string') {
      options = {content: options};
    }

    return new Promise((resolve) => {
      const instance = showModal({
        title: options.title || '提示',
        content: options.content,
        showCancel: false,
        showConfirm: true,
        confirmText: options.confirmText || '确定',
        type: options.type || 'default',
        ...options
      });

      // 监听确认和关闭事件
      instance.$once('confirm', () => {
        resolve();
      });

      instance.$once('close', () => {
        resolve();
      });
    });
  },

  /**
   * 显示成功弹窗
   * @param {Object|String} options - 弹窗配置或内容字符串
   * @returns {Promise} 返回Promise
   */
  success(options = {}) {
    if (typeof options === 'string') {
      options = {content: options};
    }

    return this.alert({
      title: options.title || '成功',
      confirmText: options.confirmText || '确定',
      type: 'success',
      ...options
    });
  },

  /**
   * 显示警告弹窗
   * @param {Object|String} options - 弹窗配置或内容字符串
   * @returns {Promise} 返回Promise
   */
  warning(options = {}) {
    if (typeof options === 'string') {
      options = {content: options};
    }

    return this.alert({
      title: options.title || '警告',
      confirmText: options.confirmText || '确定',
      type: 'warning',
      ...options
    });
  },

  /**
   * 显示错误弹窗
   * @param {Object|String} options - 弹窗配置或内容字符串
   * @returns {Promise} 返回Promise
   */
  error(options = {}) {
    if (typeof options === 'string') {
      options = {content: options};
    }

    return this.alert({
      title: options.title || '错误',
      confirmText: options.confirmText || '确定',
      type: 'error',
      ...options
    });
  },

  /**
   * 关闭所有弹窗
   */
  closeAll() {
    closeAllModals();
  }
};

export default Dialog;
